<template>
  <div class="news-detail-page">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="error-container">
      <div class="error-icon">❌</div>
      <h3>资讯加载失败</h3>
      <p>{{ error }}</p>
      <el-button @click="goBack" type="primary">返回列表</el-button>
    </div>

    <!-- 资讯详情 -->
    <div v-else-if="newsDetail" class="news-detail">
      <!-- 面包屑导航 -->
      <div class="breadcrumb">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/news' }">资讯列表</el-breadcrumb-item>
          <el-breadcrumb-item>{{ newsDetail.category }}</el-breadcrumb-item>
          <el-breadcrumb-item>{{ newsDetail.title }}</el-breadcrumb-item>
        </el-breadcrumb>
      </div>

      <!-- 资讯头部 -->
      <div class="news-header">
        <h1 class="news-title">{{ newsDetail.title }}</h1>
        <div class="news-meta">
          <span class="category-tag">{{ newsDetail.category }}</span>
          <div class="meta-info">
            <span class="publish-time">📅 {{ formatTime(newsDetail.publishTime) }}</span>
            <span class="view-count">👁 {{ newsDetail.viewCount }} 浏览</span>
            <span class="like-count">❤️ {{ newsDetail.likeCount }} 点赞</span>
          </div>
        </div>
      </div>

      <!-- 封面图片 -->
      <div v-if="newsDetail.coverImage" class="news-cover">
        <img :src="newsDetail.coverImage" :alt="newsDetail.title" />
      </div>

      <!-- 资讯内容 -->
      <div class="news-content">
        <div v-html="newsDetail.content" class="content-html"></div>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button 
          :type="isLiked ? 'danger' : 'primary'" 
          @click="handleLike"
          :loading="likeLoading"
        >
          <el-icon><Star /></el-icon>
          {{ isLiked ? '取消点赞' : '点赞' }} ({{ newsDetail.likeCount }})
        </el-button>
        
        <el-button @click="handleShare" type="success">
          <el-icon><Share /></el-icon>
          分享
        </el-button>
        
        <el-button @click="goBack" type="info">
          <el-icon><ArrowLeft /></el-icon>
          返回列表
        </el-button>
      </div>

      <!-- 相关推荐 -->
      <div v-if="relatedNews.length > 0" class="related-news">
        <h3 class="section-title">相关推荐</h3>
        <div class="related-list">
          <div 
            v-for="news in relatedNews" 
            :key="news.id" 
            class="related-item"
            @click="goToDetail(news.id)"
          >
            <div class="related-cover">
              <img :src="news.coverImage || '/images/news-default.jpg'" :alt="news.title" />
            </div>
            <div class="related-content">
              <h4 class="related-title">{{ news.title }}</h4>
              <div class="related-meta">
                <span class="category">{{ news.category }}</span>
                <span class="time">{{ formatTime(news.publishTime) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Star, Share, ArrowLeft } from '@element-plus/icons-vue'
import { newsAPI } from '../services/apiService'

const route = useRoute()
const router = useRouter()

// 响应式数据
const loading = ref(true)
const error = ref('')
const likeLoading = ref(false)

const newsDetail = ref(null)
const relatedNews = ref([])
const isLiked = ref(false)

// 获取资讯ID
const newsId = ref(parseInt(route.params.id))

// 监听路由参数变化
watch(() => route.params.id, (newId) => {
  newsId.value = parseInt(newId)
  loadNewsDetail()
})

// 生命周期
onMounted(() => {
  loadNewsDetail()
})

// 加载资讯详情
const loadNewsDetail = async () => {
  loading.value = true
  error.value = ''
  
  try {
    const response = await newsAPI.getNewsDetail(newsId.value)
    if (response.success) {
      newsDetail.value = response.data
      loadRelatedNews()
    } else {
      throw new Error(response.message || '获取资讯详情失败')
    }
  } catch (err) {
    console.error('加载资讯详情失败:', err)
    error.value = err.message || '资讯不存在或已被删除'
    ElMessage.error(error.value)
  } finally {
    loading.value = false
  }
}

// 加载相关资讯
const loadRelatedNews = async () => {
  try {
    const response = await newsAPI.getLatestNews(4)
    if (response.success) {
      // 过滤掉当前资讯
      relatedNews.value = response.data.filter(news => news.id !== newsId.value).slice(0, 3)
    }
  } catch (err) {
    console.error('加载相关资讯失败:', err)
  }
}

// 点赞处理
const handleLike = async () => {
  if (likeLoading.value) return
  
  likeLoading.value = true
  try {
    // 这里需要实现点赞API
    // const response = await newsAPI.likeNews(newsId.value)
    
    // 模拟点赞操作
    if (isLiked.value) {
      newsDetail.value.likeCount -= 1
    } else {
      newsDetail.value.likeCount += 1
    }
    isLiked.value = !isLiked.value
    
    ElMessage.success(isLiked.value ? '点赞成功' : '取消点赞')
  } catch (err) {
    console.error('点赞操作失败:', err)
    ElMessage.error('操作失败，请重试')
  } finally {
    likeLoading.value = false
  }
}

// 分享处理
const handleShare = () => {
  if (navigator.share) {
    navigator.share({
      title: newsDetail.value.title,
      text: newsDetail.value.content ? newsDetail.value.content.substring(0, 100) : '',
      url: window.location.href
    })
  } else {
    // 复制链接到剪贴板
    navigator.clipboard.writeText(window.location.href)
    ElMessage.success('链接已复制到剪贴板')
  }
}

// 导航函数
const goToDetail = (id) => {
  router.push(`/news/${id}`)
}

const goBack = () => {
  router.push('/news')
}

// 工具函数
const formatTime = (timeStr) => {
  if (!timeStr) return ''
  const date = new Date(timeStr)
  return date.toLocaleDateString() + ' ' + date.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit' 
  })
}
</script>

<style scoped>
.news-detail-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  width: 100%;
  box-sizing: border-box;
}

.breadcrumb {
  margin-bottom: 20px;
}

.news-header {
  margin-bottom: 30px;
  border-bottom: 1px solid var(--border);
  padding-bottom: 20px;
}

.news-title {
  font-size: 2rem;
  color: var(--text);
  margin: 0 0 15px 0;
  line-height: 1.3;
}

.news-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}

.category-tag {
  background: var(--primary);
  color: white;
  padding: 4px 12px;
  border-radius: 16px;
  font-size: 0.9rem;
  font-weight: 500;
}

.meta-info {
  display: flex;
  align-items: center;
  gap: 20px;
  color: var(--muted);
  font-size: 0.9rem;
}

.news-cover {
  margin-bottom: 30px;
  border-radius: 8px;
  overflow: hidden;
}

.news-cover img {
  width: 100%;
  max-height: 400px;
  object-fit: cover;
}

.news-content {
  margin-bottom: 40px;
  line-height: 1.8;
  font-size: 1.1rem;
  color: var(--text);
}

.content-html {
  word-wrap: break-word;
}

.content-html :deep(p) {
  margin-bottom: 1.5em;
}

.content-html :deep(img) {
  max-width: 100%;
  height: auto;
  border-radius: 4px;
  margin: 1em 0;
}

.content-html :deep(h1),
.content-html :deep(h2),
.content-html :deep(h3) {
  margin: 1.5em 0 0.8em 0;
  color: var(--text);
}

.content-html :deep(ul),
.content-html :deep(ol) {
  margin: 1em 0;
  padding-left: 2em;
}

.content-html :deep(blockquote) {
  border-left: 4px solid var(--primary);
  padding-left: 1em;
  margin: 1.5em 0;
  color: var(--muted);
  font-style: italic;
}

.action-buttons {
  display: flex;
  gap: 15px;
  margin-bottom: 40px;
  flex-wrap: wrap;
}

.related-news {
  border-top: 1px solid var(--border);
  padding-top: 30px;
}

.section-title {
  margin-bottom: 20px;
  color: var(--text);
  font-size: 1.3rem;
}

.related-list {
  display: grid;
  gap: 15px;
}

.related-item {
  display: flex;
  background: var(--card);
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s;
}

.related-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(0,0,0,0.1);
}

.related-cover {
  width: 120px;
  flex-shrink: 0;
}

.related-cover img {
  width: 100%;
  height: 80px;
  object-fit: cover;
}

.related-content {
  flex: 1;
  padding: 15px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.related-title {
  margin: 0 0 8px 0;
  font-size: 1rem;
  color: var(--text);
  line-height: 1.3;
}

.related-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 0.8rem;
  color: var(--muted);
}

.loading-container {
  padding: 40px 0;
}

.error-container {
  text-align: center;
  padding: 60px 20px;
  color: var(--muted);
}

.error-icon {
  font-size: 64px;
  margin-bottom: 20px;
}

.error-container h3 {
  margin-bottom: 10px;
  color: var(--text);
}

@media (max-width: 768px) {
  .news-detail-page {
    padding: 15px;
  }
  
  .news-title {
    font-size: 1.5rem;
  }
  
  .news-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .action-buttons {
    justify-content: center;
  }
  
  .related-item {
    flex-direction: column;
  }
  
  .related-cover {
    width: 100%;
  }
  
  .related-cover img {
    height: 120px;
  }
}
</style>